
import { useState,useRef ,useEffect} from "react";
import {Tooltip ,Space,Button,Popconfirm,message  } from 'antd';
import {DeleteOutlined,CaretRightOutlined } from "@ant-design/icons";
import CamundaAPI from "@/api/CamundaApi.js";


function useProcessDefList(){



  // loading
  const [loading,setLoading] = useState(false)
  // 表格数据
  const [tableData, setTableData] = useState({
    list: [] // 数据列表
  });


  // 搜索关键字
  const [keyWords,setKeyWords] = useState("")

  // 排序信息
  const sortData = useRef({
    sortField:"depl.deploy_time_",
    sortOrder:"descend"
  })

  // 分页数据 - 用于同步计算
  const paginationData = useRef({
    current:1, // 当前页数
    pageSize:10, // 页面显示的条目数
    total:0, // 记录条目总数
    pageSizeOptions:[5,10,15,20,30,50,100] // 条目数选项
  }); 


  const columnRender = (v) => {
    return (
      <Tooltip placement="topLeft" title={v}>
          {v}
        </Tooltip>
    )
  }

  // 删除流程定义
  const deleteProcessDef = (processDefId) => {
    CamundaAPI.deleteProcessDefById(processDefId).then( r=>{
      message.success('Successful')
      search();
    })
  }


  // 表格字段
  const columnsData = useRef([
    {
      title: "ID",
      dataIndex: "procDefId",
      key: "def.id_",
      width:150,
      fixed: 'left',
      sorter: true,
      ellipsis: {
        showTitle: false,
      },
      render: columnRender
    },
    {
      title: "DefKey",
      dataIndex: "defKey",
      key: "def.key_",
      fixed: 'left',
      width:200,
      sorter: true,
      ellipsis: {
        showTitle: false,
      },
      render: columnRender
    },
    {
      title: "DefName",
      dataIndex: "defName",
      key: "def.name_",
      width:150,
      sorter: true,
      ellipsis: {
        showTitle: false,
      },
      render: columnRender
    },
    {
      title: "DefVersion",
      dataIndex: "defVersion",
      key: "def.version_",
      width:150,
      sorter: true,
      ellipsis: {
        showTitle: false,
      },
      render: columnRender
    },
    {
      title: "DeployTime",
      dataIndex: "deployTime",
      key: "depl.deploy_time_",
      width:150,
      sorter: true,
      ellipsis: {
        showTitle: false,
      },
      render: columnRender
    },
    {
      title: "Operate",
      dataIndex: "operate",
      key: "operate",
      fixed: 'right',
      align:'center',
      width:60,
      render:(text,record)=>{return <div>
<Space>
<Popconfirm placement="topLeft" title="Mark sure delete ?" onConfirm={()=>{deleteProcessDef(record.procDefId
)}} okText="Yes" cancelText="No">
    <Button type="dashed" icon={<DeleteOutlined/>} >
     
    </Button>
    </Popconfirm>

    <Button type="dashed" icon={<CaretRightOutlined />} onClick={()=>{openStartProcessModal(record.procDefId)}} >
     
    </Button>
    </Space>
      </div> }
    },
  ]);

  // 搜索数据
  const search = function (clearPage) {
    // 初始化字段排序信息
    initColumnSortInfo();
    // 打开loading
    setLoading(true);


    // 清除分页
    if(clearPage){
      paginationData.current.current = 1
    }

    // 创建处理分页和排序
    let params = {
      keyWords,
      current: paginationData.current.current,
      pageSize: paginationData.current.pageSize,      
    };

    if(sortData.current.sortOrder){
      params = {
        ...params,
        sortField:sortData.current.sortField,
        sortOrder:sortData.current.sortOrder.replace("end","")
      }
    }

    console.log("search:",params)
    
    CamundaAPI.queryProcessDefPage(params).then((r) => {
      console.log(r);

      // 设置记录总数
      paginationData.current = {
        ...paginationData.current,
        total:r.result.total
      }

      // 排序显示
      columnsData.current 

      // 设置数据列表内容
      setTableData({
        ...tableData,
        list: r.result.list,
      });

      // 关闭loading
      setLoading(false);
    }).catch( ()=>{
      // 关闭loading
      setLoading(false);
    });
  };

  // 初始化字段的排序信息 sortField:字段名   sortOrder:排序(ascend,descend,undefined)
  function initColumnSortInfo(){
    columnsData.current.forEach(item => {
      delete item.sortOrder;
      if(sortData.current.sortOrder){
        if(item.key === sortData.current.sortField){
          item.sortOrder = sortData.current.sortOrder
        }
      }
    })
  }

  const onPaginationChange = function(page,pageSize){
    console.log(`pageChange[currentPage:${page},pageSize:${pageSize}]`);
    paginationData.current = {
      ...paginationData.current,
      current:page,
      pageSize
    }
    // 查询数据
    search();
  }

  const onTableChange = function(pagination,filters,sorter){
    console.log("sortChange",sorter)

    if(sorter.column){
      sortData.current = {
        ...sortData.current,
        sortField:sorter.column.key,
        sortOrder:sorter.order
      }
    }else{
      sortData.current = {
        ...sortData.current,
        sortOrder:""
      }
    }
    search()
  }


  // onComponentDidMounted
  useEffect(()=>{
    search()
  },[])


  // ========================== 流程部署modal ============================


  const [deployModalVisible, setDeployModalVisible] = useState(false);


  function onDeployModalOk(){
    setDeployModalVisible(false)
    search()
  }

  function onDeployModalCancel(){
    setDeployModalVisible(false)
  }

  function openDeployModal(){
    setDeployModalVisible(true)
  }

  // ========================== 开启流程modal ============================
  // 开启流程modal
  const [startProcessModalVisible, setStartProcessModalVisible] = useState(false);

  // 流程定义id
  const [processDefId,setProcessDefId] = useState("");

  function openStartProcessModal(processDefId){
    setProcessDefId(processDefId)
    setStartProcessModalVisible(true)   
   
  }

  function closeStartProcessModal(){
    setStartProcessModalVisible(false)   
  }

 
  

  return  {
    startProcessModalVisible,
    openStartProcessModal,
    closeStartProcessModal,

    processDefId,

    setKeyWords,
    openDeployModal,
    onDeployModalOk,
    onDeployModalCancel,
    deployModalVisible,
    loading,
    setLoading,
    tableData,
    paginationData,
    search,
    onPaginationChange,
    onTableChange,
    columnsData
  }
}


export default useProcessDefList;